package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.UserControlDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.User;
import com.itheima.service.UserControlService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = UserControlService.class)
@Transactional
public class UserControlServiceImpl implements UserControlService {

   //注入DAO对象
    @Autowired
    private UserControlDao userControlDao;


    @Override
    public void add(User user) {
        String password = user.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(password);
        user.setPassword(encode);
        userControlDao.add(user);
    }

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) throws Exception {
        PageHelper.startPage(currentPage,pageSize);

        Page<Map> page =userControlDao.selectByCondition(queryString);

        long total = page.getTotal();
        List<Map> rows = page.getResult();
        for (Map map : rows) {
            Date birthday = (Date) map.get("birthday");
            String gender = (String) map.get("gender");
            if ("1".equals(gender)){
                map.put("gender","男");
            };
            if ("2".equals(gender)){
                map.put("gender","女");
            };
            map.put("birthday",DateUtils.parseDate2String(birthday));
        }



        return new PageResult(total,rows);
    }

    @Override
    public void delete(Integer id) {
//        System.out.println(id);

        userControlDao.deleteById(id);
    }

    @Override
    public User findById(Integer id) {
        return userControlDao.findById(id);
    }

    @Override
    public void edit(User user) {
        String password = user.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(password);
        user.setPassword(encode);
        userControlDao.edit(user);
    }

    @Override
    public List<User> findAll() {
        return userControlDao.findAll();
    }
}
